package com.ihome.excel.xlsx.engine.export;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import com.ihome.excel.xlsx.exceptions.ExcelWriteException;

public abstract class AbstractExcelExportEngine {

	/**
	 * 本次导出的总条数
	 * 
	 * @return
	 */
	public abstract int rowsTotalCount();

	/**
	 * 每次写入的行数
	 * @return
	 */
	public abstract int rowsBatchCount();

	public void export(String ruleName) {
		int rowsTotalCount = rowsTotalCount();
		int rowsBatchCount = rowsBatchCount();
		int loopCounts = rowsTotalCount / rowsBatchCount;
		int remainder = rowsTotalCount % rowsBatchCount;
		if (remainder > 0) {
			loopCounts = loopCounts + 1;
		}
		List rowsCollection = null;
		ExcelWriteEngine excelWriteEngine = new ExcelWriteEngine(ruleName);
		Workbook wb = new SXSSFWorkbook(100);
		Sheet sheet = excelWriteEngine.createSheet(wb);
		for (int i = 0; i < loopCounts; i++) {
			rowsCollection = rowsCollection(i + 1);
			excelWriteEngine.write(wb,sheet, i * rowsBatchCount + 1, rowsCollection);
		}
		write(wb);
	}
	
	/**
	 * 写文件
	 * @param wb
	 */
	protected void write(Workbook wb) {
		String writePath = writePath();
		try {
			OutputStream os = new FileOutputStream(writePath);
			wb.write(os);
			os.flush();
			os.close();
		}catch(Exception e) {
			throw new ExcelWriteException(e);
		}
		
	}

	/**
	 * 每批次写入的数据集
	 * 
	 * @return
	 */
	public abstract List rowsCollection(int currentLoopIndex);
	
	/**
	 * 文件写入路径
	 * @return
	 */
	public abstract String writePath();
}
